package com.york.jobmew.gateway.exception;

import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.york.jobmew.gateway.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关全局异常处理
 * 统一处理异常，实现ErrorWebExceptionHandler接口的handle方法，根据请求处理异常信息
 */
@Component
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpRequest request = serverWebExchange.getRequest();
        ServerHttpResponse response = serverWebExchange.getResponse();

        // 0.日志处理
        log.error("网关异常 [Method:{}][Path:{}][Error:{}]",
                request.getMethod(),
                request.getPath(),
                throwable.getMessage(),
                throwable); // 包含完整堆栈

        // 1.定义默认code和message
        Integer code = 200;
        String message = "";

        // 2.结合业务自定义异常处理
        if (throwable instanceof SaTokenException) {
            code = 401;
            message = "当前用户无权限";
        } else {
            code = 500;
            message = "当前系统繁忙";
        }

        // 3.封装返回实体
        Result result = Result.fail(code, message);

        // 4.生成响应并返回
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            byte[] bytes = null;
            try {
                bytes = objectMapper.writeValueAsBytes(result);
            } catch (JsonProcessingException e) {
                log.error("网关返回响应时序列化异常 [Method:{}][Path:{}][Error:{}]",
                        request.getMethod(),
                        request.getPath(),
                        e);
            }
            return dataBufferFactory.wrap(bytes);
        }));
    }

}
